<template>
  <!--修改表单-->
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
          v-model="editUser.editValue"
          :name="editUser.editKey"
          :label="editUser.editName"
          :placeholder="`请输入${editUser.editName}`"
      />
    </van-cell-group>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        修改
      </van-button>
    </div>
  </van-form>

</template>

<script setup>
import {useRoute, useRouter} from "vue-router";
import {ref} from "vue";
import {showFailToast, showSuccessToast} from "vant";
import {getCurrentUser} from "../../sevices/User.ts";
import {updateUserInfo} from "../../api/User.ts";

const route = useRoute();
const router = useRouter();

// 修改表单值
const editUser = ref({
  editKey: route.query.editKey,
  editValue: route.query.editValue,
  editName: route.query.editName
})

// 点击修改触发的修改
const onSubmit = async (values) => {
  // 获取当前用户
  const currentUser = await getCurrentUser();
  if (!currentUser) {
    showFailToast('用户未登录');
    return;
  }
  if(editUser.value.editKey === 'gender'){
    editUser.value.editValue = editUser.value.editValue === '男' ? 0 : 1;
  }
  console.log(editUser.value);
  const result = await updateUserInfo(currentUser.id, editUser.value.editKey, editUser.value.editValue)


  if (result.code === 0 && result.data) {
    showSuccessToast('修改成功');
    router.back();
  } else {
    showFailToast('修改失败,' + (result.description ? `${result.description}` : ''));
  }
};


</script>

<style scoped>

</style>